package com.dycong.common.IO.calculator.nio;
import com.dycong.common.IO.utils.Calculator;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * com.dycong.common.IO.nio?????
 * @author yangtao__anxpp.com
 * @version 1.0
 */
public class ServerHandle implements Runnable{
	private Selector selector;
	private ServerSocketChannel serverChannel;
	private volatile boolean started;
	/**
	 * ??????
	 * @param port ?????????????
	 */
	public ServerHandle(int port) {
		try{
			//?????????
			selector = Selector.open();
			//????????
			serverChannel = ServerSocketChannel.open();
			//???? true???????????????????????????? false???????????????????????
			serverChannel.configureBlocking(false);//????????????
			//???? backlog???1024
			serverChannel.socket().bind(new InetSocketAddress(port),1024);
			//?????????????????
			serverChannel.register(selector, SelectionKey.OP_ACCEPT);
			//?????????????
			started = true;
			System.out.println("???????????????????" + port);
		}catch(IOException e){
			e.printStackTrace();
			System.exit(1);
		}
	}
	public void stop(){
		started = false;
	}
	@Override
	public void run() {
		//???????selector
		while(started){
			try{
				//????????ж?д?????????selector???1s?????????

				int i=selector.select(1000);
				System.out.println(i);
				//????,??е?????????????????????????????.
//				selector.select();
				Set<SelectionKey> keys = selector.selectedKeys();
				Iterator<SelectionKey> it = keys.iterator();
				SelectionKey key = null;
				while(it.hasNext()){
					key = it.next();
					it.remove();
					try{
						handleInput(key);
					}catch(Exception e){
						if(key != null){
							key.cancel();
							if(key.channel() != null){
								key.channel().close();
							}
						}
					}
				}
			}catch(Throwable t){
				t.printStackTrace();
			}
		}
		//selector??????????????????????
		if(selector != null)
			try{
				selector.close();
			}catch (Exception e) {
				e.printStackTrace();
			}
	}
	private void handleInput(SelectionKey key) throws IOException{
		if(key.isValid()){
			//?????????????????
			if(key.isAcceptable()){
				ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
				//???ServerSocketChannel??accept????SocketChannel???
				//???ò?????ζ?????TCP?????????TCP??????·???????
				SocketChannel sc = ssc.accept();
				//?????????????
				sc.configureBlocking(false);
				//??????
				sc.register(selector, SelectionKey.OP_READ);
			}
			//?????
			if(key.isReadable()){
				SocketChannel sc = (SocketChannel) key.channel();
				//????ByteBuffer???????????1M???????
				ByteBuffer buffer = ByteBuffer.allocate(1024);
				//????????????????????????????
				int readBytes = sc.read(buffer);
				//????????????????б????
				if(readBytes>0){
					//?????????????limit?????position=0????????????????????????
					buffer.flip();
					//????????????????????????????
					byte[] bytes = new byte[buffer.remaining()];
					//?????????????????鸴??????????????
					buffer.get(bytes);
					String expression = new String(bytes,"UTF-8");
					System.out.println("??????????????" + expression);
					//????????
					String result = null;
					try{
						result = Calculator.Instance.cal(expression).toString();
					}catch(Exception e){
						result = "???????" + e.getMessage();
					}
					//??????????
					doWrite(sc,result);
				}
				//??ж??????? ????
//				else if(readBytes==0);
				//??·?????????????
				else if(readBytes<0){
					key.cancel();
					sc.close();
				}
			}
		}
	}
	//????????????
	private void doWrite(SocketChannel channel,String response) throws IOException{
		//?????????????????
		byte[] bytes = response.getBytes();
		//????????????????ByteBuffer
		ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
		//????????鸴?????????
		writeBuffer.put(bytes);
		//flip????
		writeBuffer.flip();
		//??????????????????
		channel.write(writeBuffer);
		//****???????????д??????????
	}
}
